import hudson.model.*;

pipeline {
    //agent {
        //node {
        //    label "label-agent-lufei"
        //    customWorkspace "${env.JOB_NAME}/${env.BUILD_NUMBER}"
        //}
    //}
    agent any

    parameters {
        string(name: 'INPUT_JSON', defaultValue: 'C:\\Jenkins\\test.json', description: '')
        booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '')
        choice(name: 'ENV_TYPE', choices: ['test', 'dev', 'product', 'lufei'], description: 'test means test env,….')
        gitParameter branchFilter: 'origin/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH'
    }

    stages {
        stage('Hello') {
            steps {
                wrap([$class: 'BuildUser']) {
                    echo env.BUILD_USER
                    echo env.BUILD_USER_EMAIL
                    echo env.BUILD_NUMBER
                    bat "dir"
                    //sh "pwd"
                }
            }
        }
        
        stage("Init paramters in json") {
            steps {
                script {
                    json_file = INPUT_JSON ? INPUT_JSON : ""
                    Boolean isExists = fileExists json_file
                    if (!isExists) {
                        println "The File does not exists."
                        error "This pipeline stops here!"
                    }
                    prop = readJSON file : json_file
                    name = prop.NAME ? prop.NAME : ""
                    println "Name: " + name
                }
            }
        }
        stage("call a method") {
            when {
			    expression {
			        return (false == true || false == true)
			    }
			}
			steps {
			    script {
					println "send the parameter as map type"
					model_call = load env.WORKSPACE + "/groovy/projectA-model.groovy"
					model_call.getUserInfo(name:name, age:age, phone:phone, address:address, email:email, gender:gender, is_marry:is_marry)
				}
			}
        }
        stage('Checkout') { 
            steps {
                dir("C:\\GasErpwyy2021") {
                    script {
                        println "Checkout" 
                        checkout scmGit(
                            branches: [[name: 'refs/heads/' + BRANCH]], 
                            extensions: [], 
                            userRemoteConfigs: [[
                                credentialsId: 'lufei.git', 
                                url: 'http://192.168.2.180:8808/r/GasErpwyy2021.git'
                            ]]
                        )

                        String gitBranch = getBranch()
                        println("分支: " + gitBranch)

                        List<String> gitChangedFiles = getChangedFiles()
                        println("文件变更列表: " + gitChangedFiles)
                        
                        String gitCommitsId = getCommitsId()
                        println("CommitID: " + gitCommitsId)
                        
                        String gitCommitsAuthor = getCommitsAuthor()
                        println("提交人: " + gitCommitsAuthor)
                        
                        String gitCommitsMessage = getCommitsMessage()
                        println("提交信息: " + gitCommitsMessage)
                    }
                }
            }
        }
        stage('Build') { 
            steps {
                println "Build" 
            }
        }
        stage('Test') { 
            steps {
                println "Test" 
            }
        }
        stage('Deploy') {
            // parallel中的stage同时运行， 并行
            // failFast true    // 里面有一个stage{…}运行失败就强制停止
            parallel {
                stage('Deploy.lufei') { 
                    when {
                        expression {
                            return ENV_TYPE == 'lufei'
                        }
                    }
                    agent { label 'label-agent-lufei' } 
                    steps {
                        println "Deploy.lufei" 
                    }
                }
                stage('Deploy.dev') { 
                    when {
                        expression {
                            return ENV_TYPE == 'dev'
                        }
                    }
                    steps {
                        println "Deploy.dev" 
                    }
                }
            }
        }
        stage('Warmup') { 
            options {
                retry(3)
            }
            steps {
                println "Warmup" 
            }
        }
    }

    post {
        success {
            wrap([$class: 'BuildUser']) {
                echo '恭喜您，构建成功！！！'
                mail subject: "'${env.JOB_NAME} [${env.BUILD_NUMBER}]' 执行成功",
                body: """
                    <div id="content">
                    <h1>CI报告</h1>
                    <div id="sum2">
                        <h2>Jenkins 运行结果</h2>
                        <ul>
                        <li>jenkins的执行结果 : <a>jenkins 执行成功</a></li>
                        <li>jenkins的Job名称 : <a id="url_1">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a></li>
                        <li>jenkins的URL : <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                        <li>jenkins项目名称 : <a>${env.JOB_NAME}</a></li>
                        <li>Job URL : <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                        <li>构建日志：<a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                        </ul>
                    </div>
                    <div id="sum0">
                    <h2>GIT 信息</h2>
                    <ul>
                        <li>GIT项目的地址 : <a>${env.BRANCH}</a></li>
                        <li>GIT项目当前的分支名 : ${getBranch()}</li>
                        <li>GIT最后一次提交的commitID : ${getCommitsId()}</li>
                        <li>GIT最后一次提交人 : ${env.git_commit_name}</li>
                        <li>GIT最后一次提交邮箱 : ${env.git_commit_email}</li>
                    </ul>
                    </div>
                    </div>
                    """,
                charset: 'utf-8',
                from: 'ifelse01@163.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}"
                //to : "${Recipient}"
            }
        }
        failure {
            wrap([$class: 'BuildUser']) {
                echo '抱歉，构建失败！！！'
                mail subject: "'${env.JOB_NAME} [${env.BUILD_NUMBER}]' 执行失败",
                body: """
                <div id="content">
                <h1>CI报告</h1>
                <div id="sum2">
                    <h2>Jenkins 运行结果</h2>
                    <ul>
                    <li>jenkins的执行结果 : <a>jenkins 执行失败</a></li>
                    <li>jenkins的Job名称 : <a id="url_1">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a></li>
                    <li>jenkins的URL : <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                    <li>jenkins项目名称 : <a>${env.JOB_NAME}</a></li>
                    <li>Job URL : <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                    <li>构建日志：<a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                    </ul>
                </div>
                <div id="sum0">
                <h2>GIT 信息</h2>
                <ul>
                    <li>GIT项目的地址 : <a>${env.BRANCH}</a></li>
                    <li>GIT项目当前的分支名 : ${getBranch()}</li>
                    <li>GIT最后一次提交的commitID : ${getCommitsId()}</li>
                    <li>GIT最后一次提交人 : ${env.git_commit_name}</li>
                </ul>
                </div>
                </div>
                """,
                charset: 'utf-8',
                from: 'ifelse01@163.com',
                mimeType: 'text/html',
                to: "${getCommitsEmail()} ${env.BUILD_USER_EMAIL}"
            }
        }
    }
}

@NonCPS
// 获取分支
def getBranch() {
    def ref = ""
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            ref = entry.refName
        }
    }
    return ref
}

// 获取变更文件列表，返回HashSet， 注意添加的影响文件路径不包含仓库目录名
def getChangedFiles() {
    def changedFiles = []
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            changedFiles.add(entry.affectedPaths)
        }
    }
    return changedFiles
}

// 获取提交ID
def getCommitsId() {
    def commits_id = ""
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            commits_id = entry.commitId
        }
    }
    return commits_id
}

// 获取提交人
def getCommitsAuthor() {
    def commits_author = ""
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            commits_author = entry.author.fullName
        }
    }
    return commits_author
}

// 获取提交人的邮箱    
def getCommitsEmail() {
    def commits_email = ""
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            commits_email = entry.author.emailAddress
        }
    }
    return commits_email
}   

// 获取提交信息
def getCommitsMessage() {
    def commits_message = ""
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            commits_message = entry.msg
        }
    }
    return commits_message
}